package com.xjy.study.tdd;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xujieyang on 2016/12/9.
 */
public class Template {
    private Map<String, String> variables;
    private String templateText;

    public Template(String templateText) {
        this();
        this.templateText = templateText;
    }

    public Template() {
        variables = new HashMap<>();
    }

    public void setTemplateText(String templateText) {
        this.templateText = templateText;
    }

    public void setVariableValue(String variable, String value) {
        this.variables.put(variable, value);
    }

    // 解析模板文本
    // 1:将变量替换
    // 2:处理异常
    public String evaluate() {
        // 保持函数的抽象层次一致
        TemplateParser parser = new TemplateParser();
        List<String> segments = parser.parse(templateText);
        return concatenate(segments);
    }

    private String concatenate(List<String> segments) {
        StringBuilder result = new StringBuilder();
        for (String segment : segments) {
            appendToResult(result, segment);
        }
        return result.toString();
    }

    private void appendToResult(StringBuilder result, String segment) {
        if (isVariable(segment)) {
            replaceVariable(result, segment);
        } else {
            result.append(segment);
        }
    }

    private boolean isVariable(String segment) {
        return segment.startsWith("${") && segment.endsWith("}");
    }

    private void replaceVariable(StringBuilder result, String segment) {
        String key = segment.substring(2, segment.length() - 1);
        if (!variables.containsKey(key)) {
            throw new MissingValueException("No value for " + key);
        }
        result.append(variables.get(key));
    }
}
